package suanzi.core.db.aspect;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import suanzi.core.db.DB.DBContextHolder;
import suanzi.core.db.DB.DynamicDataSource;
import suanzi.core.db.entity.SysDatabase;
import suanzi.core.db.service.ISysDataBaseService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * 注解方式切换数据库
 */
@Aspect
@Component
public class AopDateSource {

    private static Logger logger = LoggerFactory.getLogger(AopDateSource.class);

    @Resource
    private ISysDataBaseService dataBaseService;
    @Autowired
    private DynamicDataSource dynamicDataSource;

    @Pointcut("execution(public * suanzi.core.db.controller.*.*(..)) ")
    public void data() {
    }

    /**
     * 功能描述: 用@Before标识的方法为前置方法，在目标方法的执行之前执行，即在连接点之前进行执行。
     */
    @Before("data()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();

            // 此处可以用token
            String companyId = request.getHeader("companyId");
            logger.info("------参数列表:[" + companyId + " ]");

            if (StringUtils.isNotEmpty(companyId)) {

                //默认切换到主数据源,进行整体资源的查找
                DBContextHolder.clearDataSource();
                SysDatabase dataBase = dataBaseService.getDateSourceCache(companyId);
                logger.info("Ip=====" + dataBase.getIp());

                dynamicDataSource.createDataSourceWithCheck(dataBase);
                //切换到该数据源
                DBContextHolder.setDataSource(dataBase.getDatebasename());
            }

        } catch (Exception e) {
            logger.error("获取数据源异常:" + e);
            e.printStackTrace();
        }
    }

}
